import type {
  Alias,
  BuildOptions,
  Plugin,
  UserConfig,
} from 'vite'
import fs from 'node:fs'
import { createRequire, builtinModules } from 'node:module'


const builtins = builtinModules.filter(m => !m.startsWith('_'))

const require = createRequire(import.meta.url)

const electronBuiltins = [
  'electron',
  ...builtins,
  ...builtins.map(module => `node:${module}`),
]
// 虚拟模块名称
const virtualFibModuleId = 'virtual:fib';
// Vite 中约定对于虚拟模块，解析后的路径需要加上`\0`前缀
const resolvedFibVirtualModuleId = '\0' + virtualFibModuleId;

export default function VitePluginElectronTry (options: any): Plugin {
  console.log(options)
  // console.log(electronBuiltins)
  // console.log(import.meta.url)
  // console.log(new RegExp(`^(?:node:)?(${['electron', ...builtins].join('|')})$`))
  return {
    name: 'vite-plugin-electron-try',
    async config (config, env) {
      console.log('-------config--------')
      // console.log(config)
      if (config.resolve.alias) {
        // console.log(env)
        //@ts-ignore
        config.resolve.alias = [
          {
            find: 'utils',
            replacement: 'C:\\Sergeo_Wang\\WorkSpace\\electron-vite\\src\\utils',
          },
          {
            find: 'electron',
            // https://github.com/rollup/plugins/blob/alias-v5.0.0/packages/alias/src/index.ts#L90
            replacement: 'electron',
            async customResolver (source) {
              const file = 'C:\\Sergeo_Wang\\WorkSpace\\electron-vite\\node_modules\\.vite-electron-renderer\\electron.mjs'
              // const file = 'C:\\Sergeo_Wang\\WorkSpace\\electron-vite\\src\\utils\\logs.ts'
              console.log('--------------------')
              console.log(source)
              console.log('#################')
              // fs.writeFileSync( // lazy build
              //   file,
              //   `export const logs = () => {
              //     console.log('This is a example')
              //   }`
              // )
              // plugins\electron.ts
              return { id: file }
            },
          }
        ]
      }

    },
  }
}
